package com.pinyougou.sellergoods.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.pinyougou.mapper.ItemCatMapper;
import com.pinyougou.pojo.ItemCat;
import com.pinyougou.service.ItemCatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Service(interfaceName = "com.pinyougou.service.ItemCatService")
@Transactional
public class ItemCatServiceImpl implements ItemCatService
{
    @Autowired
    private ItemCatMapper itemCatMapper;

    /**
     * 根据parent_id查询类目
     *
     * @param parentId
     */
    @Override
    public List<ItemCat> findByParentId(Long parentId)
    {
        ItemCat itemCat = new ItemCat();
        itemCat.setParentId(parentId);
        return itemCatMapper.select(itemCat);
    }

    /**
     * 添加方法
     *
     * @param itemCat
     */
    @Override
    public void save(ItemCat itemCat)
    {
        itemCatMapper.insertSelective(itemCat);

    }

    /**
     * 修改方法
     *
     * @param itemCat
     */
    @Override
    public void update(ItemCat itemCat)
    {
        itemCatMapper.updateByPrimaryKeySelective(itemCat);
    }

    /**
     * 根据主键id删除
     *
     * @param id
     */
    @Override
    public void delete(Serializable id)
    {

    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    public void deleteAll(Serializable[] ids)
    {
        List<Long> idList = new ArrayList<>();
        for (Serializable id : ids)
        {
            idList.add((Long)id);
            findIdByRecursion(id,idList);
        }
        Example example = new Example(ItemCat.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id",idList);
        itemCatMapper.deleteByExample(example);

    }

    /** 递归查找 id */
    private void findIdByRecursion(Serializable id, List<Long> idList)
    {
        List<ItemCat> itemCats = findByParentId((Long)id);
        if(itemCats != null && itemCats.size()>0)
        {
            for (ItemCat itemCat : itemCats)
            {
                idList.add(itemCat.getId());
                findIdByRecursion(itemCat.getId(),idList);
            }
        }
    }

    /**
     * 根据主键id查询
     *
     * @param id
     */
    @Override
    public ItemCat findOne(Serializable id)
    {
        return null;
    }

    /**
     * 查询全部
     */
    @Override
    public List<ItemCat> findAll()
    {
        return null;
    }
}